/**
 * C端订单列表
 */
import React from 'react';
import { Spin, Table } from 'antd';
import { clone } from 'mathjs';
import { history } from 'react-router-dom';
import { ElExport, ElNotification, ElSearchTable } from '@/components/el';
import { ExpandableConfig } from 'rc-table/lib/interface';
import {
  getTableSearchFormItems,
  getTableActionButtons,
  getTableColumns,
  getOrderInfoColumns
} from './config';

import { getOrderList, findDetailById } from '../service';
import { asserts } from '@/utils';
import dayjs from 'dayjs';
import { commonExport } from '@/utils/utils';

interface Props {
  match: any;
  history: history;
  expandedRowRender: ExpandableConfig<any>;
  push: any;
}

interface State {
  paramsData: any;
  loading: boolean;
  selectedRowKeys: Array<any>;
  expandTableLoadingMap: { [key: string]: any };
  expandTableDataMap: { [key: string]: any };
  expandedRowKeys: any;
}

class WorkOrderList extends React.Component<Props, State> {
  constructor(props) {
    super(props);
    this.state = {
      loading: false, //页面级loading
      paramsData: {}, //searchTable搜索条件存储
      selectedRowKeys: [], //选中行key值
      expandTableLoadingMap: {}, //展开行loading
      expandTableDataMap: {}, ///展开行数据
      expandedRowKeys: [] //展开行的id
    };
  }
  tableRef: any; //searchTableref
  exportRef: any; //导出组件ref

  /**
   * 列表按钮事件
   * @param name
   * @param value {selectedRowKeys, selectedRows}
   */
  handleButton = async (name, value) => {
    const { selectedRowKeys } = value;
    // 导出
    if (name === 'export') {
      const currentColumnsData = this.tableRef.getCurrentColumns(); //获取当前table的列
      const exportColumn = [];
      currentColumnsData.map((v) => {
        //组合后端所需列导出的数据格式
        exportColumn.push({
          title: v?.title,
          field: v?.dataIndex
        });
      });
      this.setState({ loading: true });
      commonExport({
        url: '/yst-order/order/salSo/twExport',
        params: {
          ...this.state.paramsData,
          idList: selectedRowKeys, //支持按行导出
          exportColumn: exportColumn, //支持按列导出
          orders: [
            {
              asc: false,
              column: 'createTime'
            }
          ]
        },
        method: 'POST',
        fileName: '服务类订单导出'
      }).then(() => {
        this.setState({ loading: false });
      });
    }
  };

  /**
   * 展开行点击
   * @param expanded
   * @param row
   */
  expand = async (expanded, row) => {
    if (expanded) {
      this.setState({
        expandTableLoadingMap: {
          ...this.state.expandTableLoadingMap,
          [row.id]: true
        }
      });
      const res = await findDetailById(row.id);
      this.setState({
        expandTableLoadingMap: {
          ...this.state.expandTableLoadingMap,
          [row.id]: false
        }
      });

      if (res && res.success) {
        const newdata = res?.data?.map((x) => {
          return {
            ...x,
            demandDate: asserts.isExist(x?.demandDate)
              ? dayjs(x?.demandDate).format('YYYY-MM-DD')
              : null, //要求交货日期
            planServiceDate: asserts.isExist(x?.planServiceDate)
              ? dayjs(x?.planServiceDate).format('YYYY-MM-DD')
              : null
          };
        });
        this.setState({
          expandTableDataMap: {
            ...this.state.expandTableDataMap,
            [row.id]: newdata
          }
        });
      } else {
        ElNotification({
          type: 'error',
          message: res.message || res.data || '操作失败！'
        });
      }
    }
  };

  /**
   * 展开行
   * @param record
   * @returns
   */
  expandedRowRender = (record) => {
    return (
      <Table
        bordered
        rowKey='id'
        size='small'
        scroll={{ x: 'min-content', y: 550 }}
        columns={getOrderInfoColumns()}
        loading={this.state.expandTableLoadingMap[record.id]}
        dataSource={this.state.expandTableDataMap[record.id]}
        pagination={false}
      />
    );
  };

  render() {
    const { loading, paramsData, selectedRowKeys } = this.state;
    return (
      <Spin spinning={loading}>
        <ElSearchTable
          tableId='b2b_order_salOrderCQueryList'
          rowKey='id'
          expandable={{
            expandedRowRender: this.expandedRowRender,
            onExpand: this.expand,
            expandedRowKeys: this.state.expandedRowKeys,
            onExpandedRowsChange: (expandedRows) => {
              this.setState({ expandedRowKeys: expandedRows });
            }
          }}
          rowSelectionConfig={{
            type: 'checkbox',
            fixed: true,
            disabledRowIds: [],
            onChange: ({ selectedRowKeys }) => {
              this.setState({
                selectedRowKeys
              });
            }
          }}
          tableProxy={{
            request: async (params) => {
              const newParams = clone(params);
              // 处理分页查询入参的日期
              Object.keys(newParams).forEach((key) => {
                !!newParams[key] &&
                  (function () {
                    if (key === 'docTime' && newParams[key]) {
                      newParams.docTimeS = !!newParams[key][0]
                        ? newParams[key][0]
                        : undefined;
                      newParams.docTimeE = !!newParams[key][1]
                        ? newParams[key][1]
                        : undefined;
                      delete newParams[key];
                    }
                  })();
              });
              // 处理分页查询入参的
              const paramData = {
                ...newParams,
                custId: newParams?.custId?.custId, //客户id
                agentEmpId: newParams?.agentEmpId?.agentEmpId, //业务员id
                orders: [{ asc: false, column: 'createTime' }], //排序
                docTypeList: ['TO', 'TB'],
                docCls: 'SO'
              };
              this.setState({
                paramsData: paramData
              });
              const res = await getOrderList(paramData);
              if (res && res.success) {
                //处理分页查询返回数据（时期处理成不带时分秒）
                res.data?.records?.forEach((x) => {
                  x.docTime = asserts.isExist(x.docTime)
                    ? dayjs(x.docTime).format('YYYY-MM-DD')
                    : ''; //日期不展示时分秒
                });
              }
              return res;
            },
            errCallBack: () => {
              console.log('err');
            },
            props: {
              success: 'success',
              result: 'data.records',
              total: 'data.total'
            },

            autoLoad: true
          }}
          scroll={{ x: 'min-content' }}
          mode={{
            // 精简模式,是否隐藏搜索表格的某一块元素
            proxy: true, // 筛选器
            search: true, // SearchForm
            action: true, // actionButtons
            pagination: true, // 分页
            descriptions: false, // descriptions
            tabs: false //下侧是否带tabs
          }}
          actionButtons={getTableActionButtons(this.handleButton)}
          searchFormProps={getTableSearchFormItems()}
          columns={getTableColumns()}
          onRef={(e) => {
            this.tableRef = e;
          }}
        />
        <ElExport
          push={this.props.push}
          prefix={'/yst-order'}
          tmplCode={'yst_order_c_export'}
          onRef={(ref) => (this.exportRef = ref)}
          queryParam={{
            ...paramsData,
            idList: selectedRowKeys
          }}
        />
      </Spin>
    );
  }
}

export default WorkOrderList;
